package com.example.keli.base.utils;

import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.Context;
import android.graphics.Color;
import android.os.Build;
import android.text.TextUtils;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.example.keli.R;
import com.example.keli.api.RetrofitManager;
import com.example.keli.api.http.api.BaseResponse;
import com.example.keli.api.http.api.subscriber.SubscriberListener;
import com.example.keli.ui.area.AreaVO;

import org.greenrobot.eventbus.EventBus;

import java.util.List;

/**
 * Description:
 * Data：2019/4/3-11:57
 * Author: Allen
 */
public class LocationManager {
    public LocationManager() {
    }

    private static LocationManager instance=null;
    public static synchronized LocationManager getInstance(){
        if(instance==null){
            instance=new LocationManager();
        }
        return instance;
    }
    private static final String NOTIFICATION_CHANNEL_NAME = "BackgroundLocation";
    private NotificationManager notificationManager = null;
    boolean isCreateChannel = false;
    LocationCall locationCall;

    @SuppressLint("NewApi")
    private Notification buildNotification(Context context) {
        Notification.Builder builder = null;
        Notification notification = null;
        if (Build.VERSION.SDK_INT >= 26) {
            //Android O上对Notification进行了修改，如果设置的targetSDKVersion>=26建议使用此种方式创建通知栏
            if (null == notificationManager) {
                notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
            }
            String channelId = context.getPackageName();
            if (!isCreateChannel) {
                NotificationChannel notificationChannel = new NotificationChannel(channelId,
                        NOTIFICATION_CHANNEL_NAME, NotificationManager.IMPORTANCE_DEFAULT);
                notificationChannel.enableLights(true);//是否在桌面icon右上角展示小圆点
                notificationChannel.setLightColor(Color.BLUE); //小圆点颜色
                notificationChannel.setShowBadge(true); //是否在久按桌面图标时显示此渠道的通知
                notificationManager.createNotificationChannel(notificationChannel);
                isCreateChannel = true;
            }
            builder = new Notification.Builder(context, channelId);
        } else {
            builder = new Notification.Builder(context);
        }
        builder.setSmallIcon(R.mipmap.app_icon)
                .setContentTitle("可哩")
                .setContentText("正在后台运行")
                .setWhen(System.currentTimeMillis());

        if (Build.VERSION.SDK_INT >= 16) {
            notification = builder.build();
        } else {
            return builder.getNotification();
        }
        return notification;
    }

    //声明AMapLocationClient类对象
    public AMapLocationClient mLocationClient = null;

    public void initLocation(Context context,LocationCall locationCall) {
        //初始化定位
        mLocationClient = new AMapLocationClient(context);
        //设置定位回调监听
        mLocationClient.setLocationListener(mLocationListener);
        this.locationCall = locationCall;
        AMapLocationClientOption option = new AMapLocationClientOption();
        /**
         * 设置定位场景，目前支持三种场景（签到、出行、运动，默认无场景）
         */
        option.setLocationPurpose(AMapLocationClientOption.AMapLocationPurpose.SignIn);
        option.setLocationMode(AMapLocationClientOption.AMapLocationMode.Battery_Saving);
        //获取一次定位结果：
        //该方法默认为false。
        option.setOnceLocation(true);
        //获取最近3s内精度最高的一次定位结果：
        //设置setOnceLocationLatest(boolean b)接口为true，启动定位时SDK会返回最近3s内精度最高的一次定位结果。如果设置其为true，setOnceLocation(boolean b)接口也会被设置为true，反之不会，默认为false。
        option.setOnceLocationLatest(true);
        if (null != mLocationClient) {
            mLocationClient.setLocationOption(option);
            //启动后台定位，第一个参数为通知栏ID，建议整个APP使用一个
            mLocationClient.enableBackgroundLocation(2001, buildNotification(context));
            //设置场景模式后最好调用一次stop，再调用start以保证场景模式生效
            mLocationClient.stopLocation();
            mLocationClient.startLocation();
        }
    }

    //声明定位回调监听器
    public AMapLocationListener mLocationListener = new AMapLocationListener() {
        @Override
        public void onLocationChanged(AMapLocation aMapLocation) {
            LogUtils.loge("tamdlj>>>定位的地址>>>>" + aMapLocation.getCity() + aMapLocation.getAddress() + aMapLocation.getProvince());
            //关闭后台定位，参数为true时会移除通知栏，为false时不会移除通知栏，但是可以手动移除
            mLocationClient.disableBackgroundLocation(true);
            if (TextUtils.isEmpty(aMapLocation.getCity())) {
                AreaVO areaVO = new AreaVO();
                areaVO.setId(-1);
                areaVO.setPid(-1);
                areaVO.setName("定位失败");
                areaVO.setaMapLocation(aMapLocation);
                locationCall.suc(areaVO);
                EventBus.getDefault().post(areaVO);
            } else {
                getRegions(aMapLocation);
            }
        }
    };

    private void getRegions(final AMapLocation aMapLocation) {
        RetrofitManager.ApiFunc(RetrofitManager.mApiService.getActivityRegion(), new SubscriberListener<BaseResponse<List<AreaVO>>>() {
            @Override
            public void onSuccess(BaseResponse<List<AreaVO>> response) {
                for (AreaVO areaVO : response.getData()) {
                    if (TextUtils.equals(areaVO.getName(), aMapLocation.getCity())) {
                        //匹配到城市。获取城市id
                        areaVO.setaMapLocation(aMapLocation);
                        EventBus.getDefault().post(areaVO);
                        locationCall.suc(areaVO);
                        return;
                    }
                }
                AreaVO areaVO = new AreaVO();
                areaVO.setId(-1);
                areaVO.setPid(-1);
                areaVO.setName(aMapLocation.getCity());
                areaVO.setaMapLocation(aMapLocation);
                EventBus.getDefault().post(areaVO);
                locationCall.suc(areaVO);
            }

            @Override
            public void onFailer(String msg) {

            }

            @Override
            public void onTokenError() {

            }
        });
    }

    public interface LocationCall{
        void suc(AreaVO areaVO);
    }
}
